package com.quartz.jobTask;

import com.utility.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *  job 定时任务 创建运行实例
 * @author HeWei123
 */
@Component
@Slf4j
public class JobExecute {


    @Autowired
    private Scheduler scheduler;


    /**
     * 功能: 移除一个任务
     * @param jobKey   定时任务实例
     * @param triggerKey  触发器实例
     */
    public void removeJob(JobKey jobKey, TriggerKey triggerKey) {
        try {
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *  创建 Job运行实例
     *  创建Job定时工作
     * @param messageInfo
     * @throws SchedulerException
     */
    public void addJobConfig(MessageInfo messageInfo)  {
        JobDetailInstantiation jobDetailInstantiation = new TriggerInstantiation();
        JobDetail jobDetail = jobDetailInstantiation.createJobDetail(messageInfo);
        SimpleTrigger simpleTrigger = (SimpleTrigger)jobDetailInstantiation.messageStorage(messageInfo);
        try {
            scheduler.scheduleJob(jobDetail,simpleTrigger);
            scheduler.start();
            log.info("定时任务已启动，等待触发器触发执行");
        }catch (ObjectAlreadyExistsException e){
            throw new ServiceException("JobDetail instantiated name already exist");
        }catch (SchedulerException e) {
            e.printStackTrace();
        }

    }



}
